package com.atguigu.tingshu.account.receiver;

import cn.hutool.core.util.StrUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

/**
 * @author xiaoxu
 * @description:
 * @date 2024/08/24 15:55
 **/
@Slf4j
@Component
public class AccountReceiver {

    @Autowired
    private UserAccountService userAccountService;

    /**
     * 监听账户余额信息
     * @param record 消息本体:用户uid
     */
    @KafkaListener(topics = KafkaConstant.QUEUE_USER_REGISTER)
    public void processAccount(ConsumerRecord<String,String> record){

        String userId = record.value();
        if (StrUtil.isNotBlank(userId)){
        log.info("得到账户初始化信息:{}",userId);
        userAccountService.saveAccount(Long.valueOf(userId));
        }

    }
    /**
     * 监听账户扣减余额信息
     * @param record 消息本体:订单号
     */
    @KafkaListener(topics = KafkaConstant.QUEUE_ACCOUNT_MINUS)
    public void processAccountMinus(ConsumerRecord<String,String> record){
        String orderNo = record.value();
        if (StrUtil.isNotBlank(orderNo)){
            log.info("开始执行扣减:{}",orderNo);
            userAccountService.minus(orderNo);
        }
    }
    /**
     * 完成账户的解锁
     * @param record 订单号
     */
    @KafkaListener(topics = KafkaConstant.QUEUE_ACCOUNT_UNLOCK)
    public void unlock(ConsumerRecord<String, String> record) {
        String orderNo = record.value();
        if (StringUtils.isNotBlank(orderNo)) {
            log.info("【账户服务】监听到还原锁定金额消息：{}", orderNo);
            //  调用还原锁定金额
            userAccountService.unlock(orderNo);
        }
    }
}
